package com.intelligentclass.controller;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.intelligentclass.constant.UserType;
import com.intelligentclass.entity.Comment;
import com.intelligentclass.entity.Student;
import com.intelligentclass.entity.Teacher;
import com.intelligentclass.services.CommentService;
import com.intelligentclass.services.StudentService;
import com.intelligentclass.services.CollectionService;
import com.intelligentclass.services.TeacherService;
import com.intelligentclass.utils.JWTUtil;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/comment")
@CrossOrigin(origins = "*")
public class CommentController {

    private final CommentService commentService;
    private final StudentService studentService;
    private final CollectionService collectionService;

    private static final String FILE_DIRECTORY = "D://IntelligentClass/comment"; // 文件和图片保存目录
    private final TeacherService teacherService;

    @Autowired
    public CommentController(CommentService commentService, StudentService studentService, CollectionService collectionService, TeacherService teacherService) {
        this.commentService = commentService;
        this.studentService = studentService;
        this.collectionService = collectionService;
        this.teacherService = teacherService;
    }


    // 创建评论并存入本地
    @PostMapping("/create")
    public ResponseEntity<?> createComment(@RequestPart("comment") Comment comment,
                                           @RequestPart(value = "file", required = false) MultipartFile file,
                                           @RequestPart(value = "image", required = false) MultipartFile image,
                                           @RequestHeader("Authorization") String token,
                                           @RequestParam("cid") String cid,
                                           @RequestParam(value = "parentCommentId", required = false) Integer parentCommentId) {
        try {
            token = token.replace("Bearer ", "");

            DecodedJWT decodedJWT = JWTUtil.verifyToken(token);
            String username = decodedJWT.getClaim("username").asString();
            int usertype = decodedJWT.getClaim("usertype").asInt();

            Student student = studentService.searchBySno(username);
            Teacher teacher = teacherService.searchByTno(username);

            token = JWTUtil.updateToken(token);

            comment.setCommentSno(username);
            if(usertype == UserType.STUDENT) {
                comment.setCommentSname(student.getSname());
            }
            if(usertype == UserType.TEACHER) {
                comment.setCommentSname(teacher.getTname());
            }
            comment.setCommentCid(cid);

            // 设置父评论
            if (parentCommentId != null) {
                Comment parentComment = commentService.findCommentByCommentId(parentCommentId);
                if (parentComment == null) {
                    return ResponseEntity.status(404).body("Parent comment not found");
                }
                comment.setParentCommentId(parentCommentId);
            }

            // 处理并保存文件
            if (file != null && !file.isEmpty()) {
                String fileName = file.getOriginalFilename();
                Path filePath = Paths.get(FILE_DIRECTORY, fileName);
                Files.write(filePath, file.getBytes());
                comment.setCommentLink(filePath.toString());
            }

            // 处理并保存图片
            if (image != null && !image.isEmpty()) {
                String imageName = image.getOriginalFilename();
                Path imagePath = Paths.get(FILE_DIRECTORY, imageName);
                Files.write(imagePath, image.getBytes());
                comment.setCommentImage(imagePath.toString());
            }

            // 保存评论
            Comment savedComment = commentService.saveComment(comment);

            Map<String, Object> response = new HashMap<>();
            response.put("comment", savedComment);
            response.put("updatedToken", token);

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            return ResponseEntity.status(401).body("Invalid or expired token");
        }
    }


    //返回所有评论属性，其中image和file会以resource方式传回需调用download方法,like代表是否收藏，1表示收藏，0则没有
    @GetMapping("/all")
    public ResponseEntity<?> getAllComments(@RequestParam("cid") String cid,
                                            @RequestHeader("Authorization") String token,
                                            @RequestParam(value = "username", required = false) String username) {
        try {
            // 如果没有提供 username，则从 token 中提取
            if (username == null || username.isEmpty()) {
                token = token.replace("Bearer ", "");
                DecodedJWT decodedJWT = JWTUtil.verifyToken(token);
                username = decodedJWT.getClaim("username").asString();
            }

            // 获取所有评论
            List<Comment> comments = commentService.findCommentsByCid(cid);

            // 构造嵌套评论树
            List<Map<String, Object>> response = buildCommentTree(comments, username);

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            System.out.println("获取评论时发生错误: " + e);
            return ResponseEntity.status(500).body("获取评论时发生错误");
        }
    }

    private List<Map<String, Object>> buildCommentTree(List<Comment> comments, String username) {
        Map<Integer, Map<String, Object>> commentMap = new HashMap<>();

        // 转换评论为 Map
        for (Comment comment : comments) {
            Map<String, Object> commentData = new HashMap<>();
            commentData.put("id", comment.getCommentId());
            commentData.put("sno", comment.getCommentSno());
            commentData.put("sname", comment.getCommentSname());
            commentData.put("times", comment.getCommentTime());
            commentData.put("text", comment.getCommentText());

            // 检查是否已收藏（点赞）该评论
            boolean isLiked = collectionService.existsByCommentIdAndSno(comment.getCommentId(), username);
            commentData.put("like", isLiked ? 1 : 0);

            // 设置文件和图片资源的下载 URL
            commentData.put("fileResourceUrl", comment.getCommentLink() != null ? URLEncoder.encode(comment.getCommentLink(), StandardCharsets.UTF_8) : "null");
            commentData.put("imageResourceUrl", comment.getCommentImage() != null ? URLEncoder.encode(comment.getCommentImage(), StandardCharsets.UTF_8) : "null");

            commentData.put("replies", new ArrayList<>()); // 子评论列表
            commentMap.put(comment.getCommentId(), commentData);
        }

        // 构造评论树
        List<Map<String, Object>> rootComments = new ArrayList<>();
        for (Comment comment : comments) {
            if (comment.getParentCommentId() == null) {
                rootComments.add(commentMap.get(comment.getCommentId()));
            } else {
                Map<String, Object> parent = commentMap.get(comment.getParentCommentId());
                if (parent != null) {
                    List<Map<String, Object>> replies = (List<Map<String, Object>>) parent.get("replies");
                    replies.add(commentMap.get(comment.getCommentId()));
                }
            }
        }

        return rootComments;
    }

    //为resource提供下载方法
    @GetMapping("/download/file")
    public ResponseEntity<Resource> downloadFile(@RequestParam("filePath") String filePath) {
        try {
            Path path = Paths.get(filePath).toAbsolutePath().normalize();
            Resource resource = new UrlResource(path.toUri());

            if (resource.exists() && resource.isReadable()) {
                String contentType = Files.probeContentType(path);
                if (contentType == null) {
                    contentType = "application/octet-stream";
                }
                String encodedFilename = URLEncoder.encode(resource.getFilename(), StandardCharsets.UTF_8);
                return ResponseEntity.ok()
                        .contentType(MediaType.parseMediaType(contentType))
                        .header(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + encodedFilename + "\"")
                        .body(resource);
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            return ResponseEntity.internalServerError().build();
        }
    }

    // 模糊搜索评论（限定为当前课程的评论）
    @GetMapping("/search")
    public ResponseEntity<?> searchComments(@RequestParam("query") String query,
                                            @RequestParam("cid") String cid,
                                            @RequestHeader("Authorization") String token,
                                            @RequestParam(value = "username", required = false) String username) {
        try {
            // 如果没有提供 username，则从 token 中提取
            if (username == null || username.isEmpty()) {
                token = token.replace("Bearer ", "");
                DecodedJWT decodedJWT = JWTUtil.verifyToken(token);
                username = decodedJWT.getClaim("username").asString();
            }

            // 执行模糊搜索并过滤当前课程的评论
            List<Comment> matchingComments = commentService.searchCommentsByQueryAndCid(query, cid);

            // 构造响应数据
            List<Map<String, Object>> response = new ArrayList<>();
            for (Comment comment : matchingComments) {
                Map<String, Object> commentData = new HashMap<>();
                commentData.put("id", comment.getCommentId());
                commentData.put("sno", comment.getCommentSno());
                commentData.put("sname", comment.getCommentSname());
                commentData.put("times", comment.getCommentTime());
                commentData.put("text", comment.getCommentText());

                // 检查是否已收藏（点赞）该评论
                boolean isLiked = collectionService.existsByCommentIdAndSno(comment.getCommentId(), username);
                commentData.put("like", isLiked ? 1 : 0);

                // 设置文件和图片资源的下载 URL
                commentData.put("fileResourceUrl", comment.getCommentLink() != null ? URLEncoder.encode(comment.getCommentLink(), StandardCharsets.UTF_8) : "null");
                commentData.put("imageResourceUrl", comment.getCommentImage() != null ? URLEncoder.encode(comment.getCommentImage(), StandardCharsets.UTF_8) : "null");

                response.add(commentData);
            }

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            System.out.println("模糊搜索评论时发生错误: " + e);
            return ResponseEntity.status(500).body("模糊搜索评论时发生错误");
        }
    }

}
